package com.stoken.web.control;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 上传文件
 * @author lichao
 *
 */
@Controller
@RequestMapping(value = "/toFile")
public class FileControl {
	private Logger logger = LoggerFactory.getLogger(FileControl.class);

	@RequestMapping(value = "/index")
	public String index(){
		return "fileUpload/oneFileUpload";
	}
	
	/**
	 * 单文件上传
	 * @param name @RequestParam 取得name字段的值
	 * @param file 文件
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/oneFileUpload", method = RequestMethod.POST)
	public String handleFormUpload(@RequestParam("name")
	String name, @RequestParam("file")
	MultipartFile file) throws IOException {
		
		logger.info("name："+name);
		logger.info("上传文件："+file.getOriginalFilename());
		if (!file.isEmpty()) {
			 this.copyFile(file.getInputStream(), file.getOriginalFilename());
			
		} 
		return "fileUpload/success";
	}

	  /**
	   * 多文件上传
	   * @param request
	   * @param name
	   * @return
	   * @throws Exception
	   */
	  @RequestMapping(value = "/multipartFileUpload",method = RequestMethod.POST)
	     public String upload2(
	        MultipartHttpServletRequest request ,
	        @RequestParam("name") String name    // 页面上的控件值
	        ) throws Exception {
	      List<MultipartFile> files = request.getFiles("file");
	      for( int i=0; i<files.size() ;i++){
	           if(! files.get(i).isEmpty()) {
	        	   logger.info("上传文件："+files.get(i).getOriginalFilename());
	              this.copyFile(files.get(i).getInputStream(), files.get(i).getOriginalFilename());
	           }
	      }
	      logger.info("success");
	      return "fileUpload/success";
	     }
	
	  /**
	   * 写文件到本地
	   * @param in
	   * @param fileName
	   * @throws IOException
	   */
	  private void copyFile(InputStream in,String fileName) throws IOException{
		  FileOutputStream fs = new FileOutputStream("d:/upload/"
					+ fileName);
			byte[] buffer = new byte[1024 * 1024];
			//int bytesum = 0;
			int byteread = 0;
			while ((byteread = in.read(buffer)) != -1) {
				//bytesum += byteread;
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
			fs.close();
			in.close();
	  }
	  
	    @RequestMapping("/download/{fileName}")  
	    public void download(@PathVariable("fileName")  
	    String fileName, HttpServletRequest request, HttpServletResponse response)  
	            throws Exception {  
	  
	        response.setContentType("text/html;charset=utf-8");  
	        request.setCharacterEncoding("UTF-8");  
	        java.io.BufferedInputStream bis = null;  
	        java.io.BufferedOutputStream bos = null;  
	  
	        String ctxPath = request.getSession().getServletContext().getRealPath(  
	                "/")  
	                + "\\" + "images\\";  
	        String downLoadPath = ctxPath + fileName;  
	        System.out.println(downLoadPath);  
	        downLoadPath ="d:/upload/1.png";
	        try {  
	            long fileLength = new File(downLoadPath).length();  
	            response.setContentType("application/x-msdownload;");  
	            response.setHeader("Content-disposition", "attachment; filename="  
	                    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
	            response.setHeader("Content-Length", String.valueOf(fileLength));  
	            bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
	            bos = new BufferedOutputStream(response.getOutputStream());  
	            byte[] buff = new byte[2048];  
	            int bytesRead;  
	            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
	                bos.write(buff, 0, bytesRead);  
	            }  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            if (bis != null)  
	                bis.close();  
	            if (bos != null)  
	                bos.close();  
	        }  
	    }
	 
	
}
